/*

 */
package com.insigma.business.qrcode.common.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;


@Component
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger("SpringContextHolder");

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContextRef) {
        applicationContext = applicationContextRef;
    }

    public static ApplicationContext getApplicationContext() {
        while (SpringContextHolder.applicationContext == null) {
            logger.info("Spring 上下文初始化中，请等待......");
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {  }
        }
        return applicationContext;
    }

    
    @SuppressWarnings("unchecked")
    public static <T> T getBean(final String beanName) {
        /*if (SpringContextHolder.applicationContext==null) {
            throw new RuntimeException("Spring 上下文尚未初始化结束！") ;
        }*/
        while (SpringContextHolder.applicationContext==null) {
            logger.info("Spring 上下文初始化中，请等待......");
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                
            }
        }

        return (T) applicationContext.getBean(beanName);
    }


 }
